﻿#region itdc

/************************************************************************
*Copyright(C) 2015 by qsgy
 *All rights reserved. 
 *FileName:     $safeitemname$
 *Author:       oyh
 *Version:      
 *UnityVersion：
 *Date:   $time$      
 *Description:    
 *History: 
************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FSMSystem : MonoBehaviour {
    protected Dictionary<StateID, FSMState> states = new Dictionary<StateID, FSMState>();
    [SerializeField,Tooltip("当前状态的id")]
    public StateID currentStateID=StateID.Null;
    [SerializeField,Tooltip("当前状态")]
    private FSMState currentState;
    [SerializeField, Tooltip("刷新条件时间间隔")]
    public float freshTime = 0.3f;
    public event Action<FSMState,FSMState> OnStateChange;//状态改变事件
    public event Action<StateID, StateID> OnStateIdChange;

    public Dictionary<StateID,FSMState> States
    {
        get { return states; }
    }

    public FSMState CurrentState
    {
        get { return currentState; }
    }


    private void Start()
    {
        FSMState[] stts = GetComponents<FSMState>();
        foreach (var s in stts)//将挂载的状态添加进字典
        {
            states.Add(s.Id, s);
            s.InitiSystem(this);//初始化state的system字段
            s.enabled = false;//先关闭
        }
#if DEBUG
        if (states.Count == 0)
        {
            Debug.LogError("状态机没有添加任何状态");
            return;
        }
#endif
        currentState = states[currentStateID];//设置当前状态
        currentState.enabled = true;//激活当前状态
        currentState.DoBeforeEnter();
    }

    /// <summary>
    /// 改变状态
    /// </summary>
    /// <param name="changeID"></param>
    public void ChangeState(StateID changeID)
    {
        if (!states.ContainsKey(changeID)) Debug.LogError("不包含转换目标的状态");
        if (OnStateChange != null) OnStateChange(currentState, states[changeID]);//发布事件
        if (OnStateIdChange != null) OnStateIdChange(currentStateID, changeID);//发布事件
        currentState.enabled = false;//关闭前一个状态
        currentState = states[changeID];//切换当前状态
        currentStateID = changeID;
        currentState.enabled = true;//开启当前状态
        currentState.DoBeforeEnter();//进入执行
    }
}
